package com.k12.admim.utils;
import com.k12.admim.model.vo.MenuVo;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
@Slf4j
public class MenuTreeUtil {

    public static List<MenuVo>  makeListToTree(List<MenuVo> menus){
        //去重操作
        ArrayList<MenuVo> menuVos = new ArrayList<>(new HashSet<>(menus));
        List<MenuVo> parentList = menuVos.stream().filter(e -> e.getParentId() == 0).toList();
        for (MenuVo parent : parentList) {
            List<MenuVo> menusTrees = toTree(parent.getMenuId(), menus);
            parent.setChildren(menusTrees);
        }
        return parentList;
    }

    private static List<MenuVo> toTree(Long id, List<MenuVo> menus) {
        List<MenuVo> children = new ArrayList<>();
        for (MenuVo menu : menus) {
            if (menu.getParentId().equals(id)){
                List<MenuVo> treeChild = toTree(menu.getMenuId(), menus);
                menu.setChildren(treeChild);
                children.add(menu);
            }
        }
        return  children;
    }
}